import DBManager
import MQTTServer
from datetime import datetime
from flask import Flask, request, render_template, send_from_directory
from flask_cors import CORS
import json
import random

class XXIOTServer:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            host = "8.137.99.64" #测试
            # host = "127.0.0.1" #正式
            # 连接数据库
            cls._instance.db = DBManager.DBManager(host=host, database='iot', user='iot', password='NWWhKPr7Chr5dmcB')
            cls._instance.db.connect()
            # 连接MQTT
            cls._instance.mq = MQTTServer.MQTTServer()
            cls._instance.mq.topics = ["c"]
            cls._instance.mq.onMessage = cls._instance.onMQTTTMsg
        return cls._instance

    def onMQTTTMsg(self, topic, msg):# 接收到MQTT消息
        # print(f"Message received: {msg.topic} {msg.payload.decode()}")
        print(f"onMQTTTMsg{topic}--{msg}")
        if topic == "":
            if msg == "":
                print("222222")

    def getDeviceList(self, data):
        print("获取设备列表")
        userId = data.get("userId")
        sql = 'userId=%s'
        params = [userId]
        for key, value in enumerate(data):
            if key == 'userId':
                continue
            sql += f' AND {key}=%s'
            params.append(value)
        sql_res = self.db.select_data("device",where_clause=sql,params=params)
        list = []
        if sql_res:
            for d in sql_res:
                data = {
                    "type": d[0],
                    "name": d[1],
                    "mac": d[2],
                    "userId": d[3],
                    "remark": d[4],
                    "createTime": d[5],
                    "updateTime": d[6],
                    "isBind": d[7],
                    "state": d[8],
                    "data":d[9]
                }
                list.append(data)
            return {"code": 1, 'msg': "suc", 'data':{'list':list,'count':len(list)}}
        else:
            return {"code": 0, 'msg': "null",'data': {'list':list,'count':0}}

    def addDevice(self,data):
        print("添加设备")
        type = data.get("type")
        name = data.get("name")
        mac = data.get("mac")
        if not type or not name or not mac:
            return {"code": 0, 'msg': "type or  name or  mac  为空"}
        if self.db.select_data("device",where_clause=f"mac=%s",params=[mac]):
            return {"code": 0, 'msg': "mac 已存在"}

        userId = ""
        isBind = 0
        if data.get("userId"):
            userId = data.get("userId")
            isBind = 1

        remark = ""
        if data.get("remark"):
            remark = data.get("remark")

        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        columns = ["type", "name", "mac", "userId","remark",'createTime','updateTime','isBind']
        values = [type, name, mac, userId,remark,timestamp,timestamp,isBind]

        if self.db.insert_data('device', columns, values) == True:
            return {'code': 1, 'msg': '添加成功'}
        else:
            return {'code': 0, 'msg': '添加失败'}

    def deleteDevice(self, data):
        print("删除设备")
        mac = data.get("mac")
        userId = data.get("userId")
        if not mac:
            return {"code": 0, 'msg': " mac  为空"}
        sql = 'mac=%s AND userId=%s'
        params = [mac,userId]
        if self.db.delete_data('device', sql, [mac,userId]) == True:
            return {'code': 1, 'msg': '删除成功'}
        else:
            return {'code': 0, 'msg': '删除失败'}

    def binding(self, data):
        print("绑定")

    def unbind(self, data):
        print("解绑")

    def getTaskList(self, data):
        print("获取任务列表")

    def deleteTask(self, data):
        print("删除任务")

    def addTask(self, data):
        print("添加任务")



app = Flask(__name__, template_folder='./')
CORS(app)  # 启用 CORS 支持

server = XXIOTServer()

@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = '*'
    return response

@app.route('/getDeviceList', methods=['POST'])  # 获取设备列表
def getDeviceList():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.getDeviceList(check_res.get('data'))
        return json.dumps(res)

@app.route('/addDevice', methods=['POST'])  # 添加设备
def addDevice():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.addDevice(check_res.get('data'))
        return json.dumps(res)

@app.route('/deleteDevice', methods=['POST'])  # 删除设备
def deleteDevice():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.deleteDevice(check_res.get('data'))
        return json.dumps(res)

@app.route('/binding', methods=['POST'])  # 绑定
def binding():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.binding(check_res.get('data'))
        return json.dumps(res)

@app.route('/unbind', methods=['POST'])  # 解绑
def unbind():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.unbind(check_res.get('data'))
        return json.dumps(res)

@app.route('/getTaskList', methods=['POST'])  # 获取任务列表
def getTaskList():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.getTaskList(check_res.get('data'))
        return json.dumps(res)

@app.route('/deleteTask', methods=['POST'])  # 删除任务
def deleteTask():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.deleteTask(check_res.get('data'))
        return json.dumps(res)

@app.route('/addTask', methods=['POST'])  # 添加任务
def addTask():
    check_res = check(request.headers,request.json)
    if check_res.get('code') == 0:
        return json.dumps(check_res)
    else:
        res = server.addTask(check_res.get('data'))
        return json.dumps(res)

def check(headers,data):
    userId = headers.get('userId')
    if not userId:
        res = {'code': 0, 'msg': 'userId 不能为空'}
        return res
    if not data:
        res = {'code': 0, 'msg': 'data 不能为空'}
        return res
    data['userId'] = userId
    return {'code': 1, 'data': data}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8082,debug=True)